package com.udg.goodmorning.tweet;


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.preference.ListPreference;
import android.preference.PreferenceManager;

/**
 * 端末起動時イベント<br>
 * 設定がONになっている場合、ポーリングイベントをセットする。
 * @author Ippei Shimobou
 *
 */
public class BootUpStarter extends BroadcastReceiver {

	static PendingIntent sender = null;
	static AlarmManager am = null;

	@Override
	public void onReceive(Context context, Intent receivedIntent) {
		// TODO Auto-generated method stub

//		SharedPreferences cPref = context.getSharedPreferences("PreferenceMenu", context.MODE_PRIVATE);
//		boolean OnOff = cPref.getBoolean(Utility.KEY_ONOFF, false);

		SharedPreferences cPref = PreferenceManager.getDefaultSharedPreferences(context);

		boolean OnOff = cPref.getBoolean(Utility.KEY_ONOFF, false);


		if(OnOff){
			/* Setting On-Time */
			SharedPreferences OnOffPref = context.getSharedPreferences("on_off_time",
					context.MODE_PRIVATE);
			SharedPreferences.Editor editor = OnOffPref.edit();

			/* Get time */
			editor.putString("on_time",
					Long.toString(System.currentTimeMillis()));
			editor.commit();

			/* get interval time */
			String preftime = cPref.getString(Utility.KEY_TIME_LIST, "5");

			/* set Alarm Manager */
			Intent intent = new Intent(context, Receiver.class);
			intent.setAction(Utility.START_SERVICE);
			sender = PendingIntent.getBroadcast(context, 0, intent, 0);
			am = (AlarmManager)(context.getSystemService(context.ALARM_SERVICE));

			long interval = Long.valueOf(preftime) * 1000 * 60;

			if(Utility.DEBUG) interval = 1000 * 60;

			long firstTime = SystemClock.elapsedRealtime();
			am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, interval, sender);

		}

	}

}
